package com.web.crawler;

import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ElasticSearchUtil {
    private static RestHighLevelClient client;

    static {
        // 初始化客户端
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")
                )
        );
    }

    // 关闭客户端
    public static void close() throws IOException {
        if (client != null) {
            client.close();
        }
    }

    // 创建索引
    public static void createIndex(String indexName, String id, String json) throws IOException {
        IndexRequest request = new IndexRequest(indexName)
                .id(id)
                .source(json, XContentType.JSON);

        client.index(request, RequestOptions.DEFAULT);
    }

    // 搜索文档
    public static List<Map<String, Object>> search(String indexName, String field, String keyword) throws IOException {
        SearchRequest searchRequest = new SearchRequest(indexName);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 使用match查询
        sourceBuilder.query(QueryBuilders.matchQuery(field, keyword));
        searchRequest.source(sourceBuilder);

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        List<Map<String, Object>> results = new ArrayList<>();

        for (SearchHit hit : response.getHits().getHits()) {
            results.add(hit.getSourceAsMap());
        }

        return results;
    }
}